﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoBase;
using KeaoMDS.AppCode;
using KeaoMDS.Weight;
using GoldPrinter;
using System.Diagnostics;
using KeaoUpLoad;

namespace KeaoMDS.Report
{
    public partial class ChengZhongMingXi : BaseForm
    {
        private string m_ChengZhongLeiXing = string.Empty;
        public ChengZhongMingXi(string ChengZhongLeiXing)
        {
            InitializeComponent();
            m_ChengZhongLeiXing = ChengZhongLeiXing;
            if (m_ChengZhongLeiXing=="入库物料")
            {
                this.Text = "入库物料明细查询";
            }
            else
            {
                this.Text = "出库物料明细查询";
            }
        }

        private void ChengZhongMingXi_Load(object sender, EventArgs e)
        {
            grid_mingxi.AutoGenerateColumns = false;
            this.MinimumSize = this.Size;
            dateTimePicker1.Value = DateTime.Today;
            dateTimePicker2.Value = dateTimePicker1.Value.AddHours(23).AddMinutes(59).AddSeconds(59);

            BindWuLiaoMingCheng();
            BindDanWeiMingCheng();

            BindInfo();
        }

        private void BindInfo()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing, "", SearchConditionType.等于);
            if (cmb_danweimingcheng.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("danweimingcheng", DataValueCommonType.字符串, cmb_danweimingcheng.Text, "", SearchConditionType.等于);
            }
            if (cmb_wuliao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("wuliaomingcheng", DataValueCommonType.字符串, cmb_wuliao.Text, "", SearchConditionType.等于);
            }
            if (cmb_xinghao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("xinghao", DataValueCommonType.字符串, cmb_xinghao.Text, "", SearchConditionType.等于);
            }
            createCondition += KeaoUtils._DB.CreateAndCondition(m_ChengZhongLeiXing == "入库物料" ? "pizhongshijian" : "maozhongshijian", DataValueCommonType.日期时间, dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"), dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
            Dictionary<string, string> orderBy = new Dictionary<string, string>();
            orderBy.Add(m_ChengZhongLeiXing == "入库物料" ? "pizhongshijian" : "maozhongshijian", "desc");
            Dictionary<string, string> leftTables = new Dictionary<string, string>();
            leftTables.Add("tbl_biaoduan", "tbl_biaoduan.id = tbl_chengzhong.quxiangbiaoduan");
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong","tbl_chengzhong.*,tbl_biaoduan.biaoduanmingcheng",leftTables, createCondition,"", orderBy);
            DataTable DtCount = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong", "count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang", null, createCondition,null,null);
            if (Dt.Rows.Count > 0)
            {
                DataRow newRow = Dt.NewRow();
                newRow["id"] = "";
                newRow["chepaihao"] = string.Format("合计：{0}车", DtCount.Rows[0]["cheshu"]);
                newRow["maozhong"] = DtCount.Rows[0]["maozhong"];
                newRow["pizhong"] = DtCount.Rows[0]["pizhong"];
                newRow["kouzhong"] = DtCount.Rows[0]["kouzhong"];
                newRow["jingzhong"] = DtCount.Rows[0]["jingzhong"];
                newRow["fahuozhongliang"] = DtCount.Rows[0]["fahuozhongliang"];
                newRow["jisuanfangliang"] = DtCount.Rows[0]["jisuanfangliang"];
                Dt.Rows.Add(newRow);
            }

            grid_mingxi.DataSource = Dt;
            grid_mingxi.AutoResizeColumns();
        }

        private void BindDanWeiMingCheng()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, m_ChengZhongLeiXing == "入库物料" ? "入库单位" : "出库单位", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["danweimingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_danweimingcheng.DisplayMember = "danweimingcheng";
            cmb_danweimingcheng.ValueMember = "id";
            cmb_danweimingcheng.DataSource = Dt;
        }

        private void BindWuLiaoMingCheng()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaoleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing , "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("wuliaozhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_wuliao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["wuliaomingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_wuliao.DisplayMember = "wuliaomingcheng";
            cmb_wuliao.ValueMember = "id";
            cmb_wuliao.DataSource = Dt;
        }

        private void BindXingHao()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaobianhao", DataValueCommonType.字符串, cmb_wuliao.SelectedValue.ToString(), "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_xinghao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["xinghao"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_xinghao.DisplayMember = "xinghao";
            cmb_xinghao.ValueMember = "id";
            cmb_xinghao.DataSource = Dt;
        }

        private void cmb_wuliao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_wuliao.SelectedIndex != 0)
            {
                BindXingHao();
            }
            else 
            {
                cmb_xinghao.DataSource = null;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindInfo();
        }

        private void grid_mingxi_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void contextMenu_1_xiugai_Click(object sender, EventArgs e)
        {
            //修改已完成
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("已完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }
            if (grid_mingxi.SelectedRows.Count==0)
            {
                return;
            }
            int selectIndex = grid_mingxi.SelectedRows[0].Index;
            YiWanChengXiuGai yiWanChengXiuGai = new YiWanChengXiuGai(string.Format("{0}",grid_mingxi.SelectedRows[0].Cells["id"].Value),m_ChengZhongLeiXing);
            if (yiWanChengXiuGai.ShowDialog() == DialogResult.OK)
            {
                BindInfo();
                grid_mingxi.Rows[selectIndex].Selected = true;
            }
        }

        private void contextMenu_1_shanchu_Click(object sender, EventArgs e)
        {
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("已完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }
            if (grid_mingxi.SelectedRows.Count==0)
            {
                return;
            }
            if (KeaoUtils.ShowQuestionMessage("确定要删除该称重信息吗？") == DialogResult.Yes)
            {
                MainForm.RiZhi(string.Format("删除{1}已完成信息，单号：【{0}】", grid_mingxi.SelectedRows[0].Cells["col_chengzhongbianhao"].Value,m_ChengZhongLeiXing));
                if (KeaoUtils._DB.DeleteRowByID(new TableRow() { TableName = "tbl_chengzhong", ID = string.Format("{0}", grid_mingxi.SelectedRows[0].Cells["id"].Value) }) > 0)
                {
                    KeaoUtils.ShowInfoMessage("已删除。");
                    BindInfo();
                }
            }
        }

        private void contextMenu_1_bangdan_Click(object sender, EventArgs e)
        {
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("磅单补打"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }
            if (grid_mingxi.SelectedRows.Count==0)
            {
                return;
            }
            if (KeaoUtils.ShowQuestionMessage("原磅单将作废，确定要补打磅单吗？") == DialogResult.Yes)
            {
                KeaoPrinter.Print(grid_mingxi.SelectedRows[0].Cells["id"].Value,true);
            }
        }

        private void contextMenu_1_jietu_Click(object sender, EventArgs e)
        {
            if (grid_mingxi.SelectedRows.Count==0)
            {
                return;
            }
            DataTable Dt = grid_mingxi.DataSource as DataTable;
            DataRow selectRow = Dt.Select(string.Format("id='{0}'", grid_mingxi.SelectedRows[0].Cells["id"].Value))[0];
            //视频监控

            ShiPinJianKong shiPin = new ShiPinJianKong(string.Format("{0}",selectRow["maozhongtupian1"]),string.Format("{0}",selectRow["maozhongtupian2"]),string.Format("{0}",selectRow["maozhongtupian3"]),string.Format("{0}",selectRow["pizhongtupian1"]),string.Format("{0}",selectRow["pizhongtupian2"]),string.Format("{0}",selectRow["pizhongtupian3"]));
            shiPin.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable Dt = grid_mingxi.DataSource as DataTable;
            if (Dt == null)
            {
                return;
            }
            //报表导出
            if (m_ChengZhongLeiXing == "入库物料")
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\物资入库明细报表.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value,dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["danweimingcheng"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["wuliaomingcheng"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["xinghao"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["pizhongshijian"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["jingzhong"]));
                        excelAccess.SetCellText(i + 4, "F", string.Format("{0}", Dt.Rows[i]["kouzhong"]));
                        excelAccess.SetCellText(i + 4, "G", string.Format("{0}", Dt.Rows[i]["fahuozhongliang"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "G", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "G");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("入库明细报表导出失败。{0}",err.Message));
                }
                finally 
                {
                    excelAccess.Close();
                }
            }
            else
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\物资出库明细报表.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value, dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["danweimingcheng"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["wuliaomingcheng"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["xinghao"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["pizhongshijian"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["jingzhong"]));
                        excelAccess.SetCellText(i + 4, "F", string.Format("{0}", Dt.Rows[i]["kouzhong"]));
                        excelAccess.SetCellText(i + 4, "G", string.Format("{0}", Dt.Rows[i]["quxiangbiaoduan"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "G", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "G");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("出库明细报表导出失败。{0}", err.Message));
                }
                finally
                {
                    excelAccess.Close();
                }
            }
        }

        public event EventHandler OnMingXiClose;

        private void ChengZhongMingXi_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (OnMingXiClose != null)
            {
                OnMingXiClose(null, null);
            }
        }


    }
}
